<?php

// DB Definitions
define("HOST", "localhost");
define("USER", "root");
define("PASSWORD", "123456");
define("DBNAME", "projectdb");

class DBContext
{
	// singleton
	private static $instance;
	
	private function DBContext($dbuser, $dbpassword, $dbname, $dbhost)
	{
		$this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);
		
		if ( ! $this->dbh )
		{
			// error. Could not connect
		}
			
		$this->select($dbname);
	}
	
	static function Instance()
	{
		if (!isset(self::$instance))
		{
			self::$instance = new DBContext(USER, PASSWORD, DBNAME, HOST);
		}
		
		return self::$instance;
	}
	
	function select($db)
	{
		if ( !@mysql_select_db($db,$this->dbh))
		{
			// error. db cannot be selected
		}
	}
	
	function queryNoJSON($query) 
	{	
		// Kill this
		$this->last_result = null;
		$this->col_info = null;

		// Keep track of the last query for debug..
		$this->last_query = $query;
		
		// Perform the query via std mysql_query function..
		$this->result = mysql_query($query,$this->dbh);

		if ( mysql_error() )
			return mysql_error();
		else
			return true;
	}
	
	function query($query) 
	{		
		// Kill this
		$this->last_result = null;
		$this->col_info = null;

		// Keep track of the last query for debug..
		$this->last_query = $query;
		
		// Perform the query via std mysql_query function..
		$this->result = mysql_query($query,$this->dbh);

		if ( mysql_error() ) 
		{
			// If there is an error then take note of it..
		}
		else
		{
			// In other words if this was a select statement..
			if ( $this->result )
			{
				// =======================================================
				// Take note of column info
				
				$i=0;
				while ($i < @mysql_num_fields($this->result))
				{
					$this->col_info[$i] = @mysql_fetch_field($this->result);
					$i++;
				}

				// =======================================================				
				// Store Query Results
				
				$i=0;
				while ( $row = @mysql_fetch_object($this->result) )
				{ 

					// Store relults as an objects within main array
					$this->last_result[$i] = $row;
					
					$i++;
				}
				
				@mysql_free_result($this->result);

				// If there were results then return true for $db->query
				if ( $i )
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
	}
	
	function get_results($query=null)
	{				
		if ( $query )
		{
			$this->query($query);
			return $this->last_result;
		}	
		else
			return null;
	}
	
	// $selectFields should be in format like "column1, column2, column3"
	// $additionalClause - PLEASE, be AWARE of passing this parameter in wrong format.
	// examples: 'where ID = 2' or 'where FirstName = 'John''
	// returns result set.
	function GetFromTable($tblName, $selectFields, $additionalClause = null)
	{
		if ($tblName && $selectFields)
		{
			// checking for $additionalClause variable.
			// building $query according to value.
			if (!isset($additionalClause))
			{
				$query = "select $selectFields from $tblName";
			}
			else
			{
				// If not null - building $query with additional clause
				$query = "select $selectFields from $tblName $additionalClause";
			}
		}
		else return null;
		
		// executing $query
		if (isset($query))
		{
			$result = $this->get_results($query);
			
			// returning values in json format. Array of objects: [{}, {}, {}, ...]
			return json_encode($result);
		}
		else return null;
	}
	
	// NOTE
	// When inserting value into SQL Query, you shoudl know that 
	// STRING values are with character ' on both sides - 'Owner', 'AppliedMathematics'
	// And integer values should be as they are - 1,3,4
	
	
	// $colName - column which will be checked for $colValue and matched row will be deleted
	// returns boolean value. true - success, false - problem during query execution
	// or in case incorrect parameters(some values were null).
	function DeleteFromTable($tblName, $colName, $colValue)
	{
		if ($tblName && $colName && $colValue)
		{
			// building DELETE SQL statement accoring to pattern.
			$query = "delete from $tblName where $colName = $colValue";

			if (isset($query))
			{
				// executing $query. Returning execution result.
				return $this->queryNoJSON($query);
			}
			else
				return false;
		}
		else return false;
	}
	
	// $values - values to be inserted into table.
	// $values format - "value1, value2, value3"
	// $colNames - optional, in case you need to specify columns 
	// in which values should be inserted
	// returns boolean value, result of query execution.
	function InsertIntoTable($tblName, $colNames, $values)
	{
		if ($tblName && $colNames && $values)
		{		
			// building $query.
			$query = "insert into $tblName($colNames) values($values)";
			
			// executing.
			return $this->queryNoJSON($query);
		}
		else return false;
	}
	
	// $columns - string value, where all table columns are separated with comas.
	// $newValues - string value, where all new object values are separated with comas.
	// $colName, $colValue - values for searching row to be updated.
	function UpdateTableRecord($tblName, $columns, $newValues, $colName, $colValue)
	{
		if ($tblName && $newValues && $colName && $colValue)
		{
			// exploding columns and values into arrays.
			// as they were passed into method as coma-separated string
			$columnsArr = explode(',', $columns);
			$valuesArr = explode(',', $newValues);
			
			// checking for count equality, terminate process if not equals
			if (count($columnsArr) == count($valuesArr))
			{
				$count = count($columnsArr);
			}
			else
				return false;
			
			// starting $query building
			$query = "update $tblName set ";
			
			for ($counter = 0; $counter < $count; $counter++)
			{
				// adding column = value pair with coma at the end
				$query .= "$columnsArr[$counter] = $valuesArr[$counter],";
			}
			// removing last, redundant coma
			$query = substr($query, 0, strlen($query) - 1);
			
			// finalizing $query with WHERE clause
			$query .= " where $colName = $colValue";
			// executing
			return $this->queryNoJSON($query);
		}
		else
			return false;
	}
}

/*echo DBContext::Instance()->GetFromTable("user_path", "user_id,path, is_left,is_right,level,sponsor_id");*/
//DBContext::Instance()->InsertIntoTable("user_path", "path, is_left,is_right,level,sponsor_id", "'test', 0, 0, 111, 10");
//DBContext::Instance()->UpdateTableRecord("user_path", "path, level", "'mathafacka',555", "user_id", "21");
//DBContext::Instance()->DeleteFromTable("user_path", "user_id", "20");
